//
//  ATAudioInputButton.m
//  艾特智家
//
//  Created by At123456 on 16/7/26.
//  Copyright © 2016年 aite. All rights reserved.
//

#import "ATAudioInputButton.h"

static CGFloat tabbarHeight = 60;

@interface ATAudioInputButton ()

@property (nonatomic, assign)   CGFloat     topDistance;
@property (nonatomic, assign)   CGFloat     bottomDistance;
@end

@implementation ATAudioInputButton

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        self.topDistance = 0;
        self.bottomDistance = self.superview.frame.size.height;
        UIPanGestureRecognizer *audioPan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
        
        [self addGestureRecognizer:audioPan];
    }
    return self;
}

- (void) panAction:(UIPanGestureRecognizer *)gesture {
    CGPoint point = [gesture locationInView:self.superview];
    
    self.center = point;
    
    if (gesture.state == UIGestureRecognizerStateChanged) {
        
        CGRect rect = self.frame;
        
        //超出左侧边界
        if(self.frame.origin.x < 0){
            rect.origin.x = 0;
        }
        
        //超出右侧边界
        if(self.frame.origin.x > self.superview.frame.size.width -  self.frame.size.width){
            rect.origin.x = self.superview.frame.size.width -  self.frame.size.width;
        }
        
        //超出上部边界
        if(self.frame.origin.y < 0){
            rect.origin.y = 0;
        }
        
        //超出下部边界
        if(self.frame.origin.y > self.superview.frame.size.height - self.frame.size.height - tabbarHeight){
            rect.origin.y = self.superview.frame.size.height - self.frame.size.height - tabbarHeight;
        }
        
        self.frame = rect;

    }
    
    if (gesture.state == UIGestureRecognizerStateEnded) {
        
        
        CGRect rect = self.frame;
        
        if (self.center.x > self.superview.frame.size.width * 0.5) {
            rect.origin.x = self.superview.frame.size.width - self.frame.size.width;
        }
        else {
            rect.origin.x = 0;
        }
        
        if (self.frame.origin.y < self.topDistance) {
            rect.origin.y = self.topDistance;
        }
        
        if (self.frame.origin.y > self.superview.frame.size.height- self.frame.size.height - self.bottomDistance) {
            rect.origin.y = self.superview.frame.size.height - self.frame.size.height - self.bottomDistance;
        }
        
        self.frame = rect;
        
    }

}

/**
 *  超出部分点击事件
 */
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    
    UIView *view = [super hitTest:point withEvent:event];
    if (view == nil) {
        
        for (UIView *v in self.subviews) {
            
            CGPoint tempoint = [v convertPoint:point fromView:self];
            if (CGRectContainsPoint(v.bounds, tempoint))
            {
                view = v;
            }
        }
    }
    return view;
}

@end
